package model

import (
	"blogdemo/gin/errmsg"
	"fmt"
	"github.com/jinzhu/gorm"
)

type Preference struct {
	gorm.Model
	Username string `gorm:"type:varchar(20); not null" json:"username"`
	Author   string `gorm:"type:varchar(20); not null" json:"author"`
	Title    string `gorm:"type:varchar(20); not null" json:"title"`
	Attitude string `gorm:"type:varchar(20); not null" json:"attitude"`
}

// FindPreference 查找数据库中是否有偏好记录，如果有将偏好记录返回（like 和 dislike 两种）
func FindPreference(username string, author string, title string) (bool, string) {
	var preference Preference
	db.Where("username = ? and author = ? and title = ?", username, author, title).First(&preference)
	if preference.Attitude == "" {
		return false, ""
	}
	return true, preference.Attitude
}

// Upvote 没有偏好记录添加 like 的记录，有偏好记录将记录修改为 like
func Upvote(username string, author string, title string) int {
	fmt.Println(username)
	fmt.Println(author)
	fmt.Println(title)
	isExit, attitude := FindPreference(username, author, title)
	fmt.Println(isExit)
	if !isExit {
		preference := Preference{Username: username, Author: author, Title: title, Attitude: "like"}
		err := db.Create(&preference).Error
		if err != nil {
			return errmsg.FAIL
		}
	} else {
		if attitude == "dislike" {
			err := db.Model(&Preference{}).Where("username = ? and author = ? and title = ?",
				username, author, title).Update("attitude", "like").Error
			if err != nil {
				return errmsg.FAIL
			}
		}
	}
	return errmsg.SUCCESS
}

// Downvote 没有偏好记录添加 dislike 的记录，有偏好记录将记录修改为 dislike
func Downvote(username string, author string, title string) int {
	isExit, attitude := FindPreference(username, author, title)
	if !isExit {
		preference := Preference{Username: username, Author: author, Title: title, Attitude: "dislike"}
		err := db.Create(&preference).Error
		if err != nil {
			return errmsg.FAIL
		}
	} else {
		if attitude == "like" {
			err := db.Model(&Preference{}).Where("username = ? and author = ? and title = ?",
				username, author, title).Update("attitude", "dislike").Error
			if err != nil {
				return errmsg.FAIL
			}
		}
	}
	return errmsg.SUCCESS
}

// Cancel 取消点赞或踩
func Cancel(username string, author string, title string) int {
	isExit, _ := FindPreference(username, author, title)
	if isExit {
		db.Unscoped().Where("username = ? and author = ? and title = ?",
			username, author, title).Delete(&Preference{})
		return errmsg.SUCCESS
	}
	return errmsg.SUCCESS
}
